import { login } from "api/user";
const TOKEN_KEY = "token";
const USER_INFO_KEY = "user-info";
export default {
  // 独立命名空间
  namespaced: true,
  state: () => ({
    // 用户toke
    token: uni.getStorageSync(TOKEN_KEY) || "",
    // 用户信息
    userInfo: uni.getStorageSync(USER_INFO_KEY) || {},
  }),
  mutations: {
    saveToken(state) {
      uni.setStorage({
        key: TOKEN_KEY,
        data: state.token,
      });
    },
    setToken(state, token) {
      state.token = token;
      this.commit("user/saveToken");
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
      this.commit("user/saveUserInfo");
    },
    saveUserInfo(state) {
      uni.setStorage({
        key: USER_INFO_KEY,
        data: state.userInfo,
      });
    },
    /**
     * 删除 token
     */
    removeToken(state) {
      state.token = "";
      this.commit("user/saveToken");
    },
    /**
     * 删除用户信息
     */
    removeUserInfo(state) {
      state.userInfo = {};
      this.commit("user/saveUserInfo");
    },
  },
  actions: {
    async login(context, userProfile) {
      const userInfo = userProfile.userInfo;
      // 调用登录接口
      const { data: res } = await login({
        signature: userProfile.signature,
        iv: userProfile.iv,
        nickName: userInfo.nickName,
        gender: userInfo.gender,
        city: userInfo.city,
        province: userInfo.province,
        avatarUrl: userInfo.avatarUrl,
      });
      this.commit("user/setToken", res.token);
      this.commit("user/setUserInfo", userInfo);
    },
    logout(context) {
      this.commit("user/removeToken");
      this.commit("user/removeUserInfo");
    },
    async isLogin(context) {
      if (context.state.token) return true;
      // TODO: 如果用户未登录，则引导用户进入登录页面
      const [erorr, res] = await uni.showModal({
        title: "登录之后次啊可以进行后续操作",
        content: "立即跳转到登录页面？",
      });
      const { confirm, cancle } = res;
      if (confirm) {
        uni.navigateTo({ url: "/subpkg/pages/login-page/login-page" });
      }
      return false;
    },
  },
};
